<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/22/022
 * Time: 17:59
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\service\NoteCode as NoteCodeService;
use \app\api\validate\LoginValidate;
use \app\api\service\MemberToken;
use \app\api\model\Member as MemberModel;
use app\lib\exception\MemberException;

class Login extends BaseController {

    /**
     * 管理员登录验证
     * @url /login.admin_check_login
     * @http POST
     */
    public function adminCheckLogin() {
        $login_validate = new LoginValidate();
        // 验证参数
        $login_validate->goCheck('admin');
        // 根据验证规则获取参数
        $params = $login_validate->getDataByRule(input('post.'));
        // 获取管理员
        $admin = AdminModel::getAdminByUsername($params['username']);
        if (!$admin) {
            // 管理员不存在，抛出异常
            throw new AdminException();
        }
        // 验证管理员密码是否正确
        $check_admin_password = AdminService::checkAdminPassword($admin, $params['password']);
        if (!$check_admin_password) {
            // 密码错误，抛出异常
            throw new AdminException([
                'errorCode' =>  10001,
                'msg' => '密码错误'
            ]);
        }
        // 验证通过创建登录令牌
        $token = (new AdminToken())->get($admin);

        // 更新管理员登录时间
        $admin->save(['last_login_time' => time()]);

        // 添加日志
        AdminLog::addAdminLog($admin->id, '登录成功！');

        return ['token' => $token, 'msg' => 'success'];
    }


    /**
     * 用户登录验证
     * @url /login.admin_check_login
     * @http POST
     */
    public function memberCheckLogin() {
        $login_validate = new LoginValidate();
        // 验证参数
        $login_validate->goCheck('member');

        // 根据验证规则获取参数
        $params = $login_validate->getDataByRule(input('post.'));

        // 检查验证码
        NoteCodeService::VerificationCode($params);

        // 检查用户是否存在
        $member = MemberModel::getMemberByUsername($params['mobile']);
        if (!$member) {
            // 用户不存在   重新注册
            $member = MemberModel::register($params['mobile'], 'eybs' . time());
        }

        // 验证通过创建登录令牌
        $token = (new MemberToken())->get($member);

        return ['token' => $token, 'msg' => 'success'];
    }
}